//
//  Record.m
//  iOS_2D_RecordPath
//
//  Created by PC on 15/8/3.
//  Copyright (c) 2015年 FENGSHENG. All rights reserved.
//

#import "AMapRouteRecord.h"
@interface AMapRouteRecord()<NSCoding>
@property (nonatomic, strong) NSDate *startTime;
@property (nonatomic, strong) NSDate *endTime;
@property (nonatomic, strong) NSMutableArray<CLLocation *> *locationsArray;
@property (nonatomic, strong) NSMutableArray<CLLocation *> *annotationLocationsArray;
@property (nonatomic, strong) NSMutableArray *filePathArray;
@property (nonatomic, assign) CLLocationCoordinate2D *coords;
// 时间类型
@property (nonatomic, strong) NSDateFormatter *formatter;

@end

@implementation AMapRouteRecord

- (NSDateFormatter *)formatter {

    if (!_formatter) {
        _formatter = [[NSDateFormatter alloc] init];
        _formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
        _formatter.dateFormat = @"YYYY-MM-dd HH:mm:ss";
    }
    return _formatter;
}

- (NSMutableArray *)filePathArray {

    if (!_filePathArray) {
        _filePathArray = [NSMutableArray array];
    }
    
    return _filePathArray;
}



#pragma mark - interface

- (void)addLocation:(CLLocation *)location
{
    _endTime = [NSDate date];
    [self.locationsArray addObject:location];
}

- (void)addAnnotationLocation:(CLLocation *)location withImagePath: (NSString *)imagePath withAudioPath: (NSString *)audioPath {

    [self.annotationLocationsArray addObject:location];
    
    NSMutableDictionary *fileDict = [NSMutableDictionary dictionary];
    if (imagePath.length) {
        [fileDict setValue:imagePath forKey:@"imagePath"];
    }
    if (audioPath.length) {
        [fileDict setValue:audioPath forKey:@"audioPath"];
    }
    [self.filePathArray addObject:fileDict];
}

- (void)deleteAnnotationLocation {

    [self.annotationLocationsArray removeLastObject];
}

//- (NSString *)indexWithAudioFilePath:(NSInteger)index {
//    
//    // 录音文件路径
//    return [self.audioFilePathArray objectAtIndex:index];
//}

- (CLLocation *)startLocation
{
    return [self.locationsArray firstObject];
}

- (CLLocation *)endLocation
{
    return [self.locationsArray lastObject];
}

- (CLLocationCoordinate2D *)coordinates
{
    if (self.coords != NULL)
    {
        free(self.coords);
        self.coords = NULL;
    }
    
    self.coords = (CLLocationCoordinate2D *)malloc(self.locationsArray.count * sizeof(CLLocationCoordinate2D));
    
    for (int i = 0; i < self.locationsArray.count; i++)
    {
        CLLocation *location = self.locationsArray[i];
        self.coords[i] = location.coordinate;
    }
    
    return self.coords;
}

- (NSArray<CLLocation *> *)locations
{
    return [self.locationsArray copy];
}

- (NSArray<CLLocation *> *)annotationLocations
{
    return [self.annotationLocationsArray copy];
}

- (NSArray<NSDictionary *> *)filePaths {

    return [self.filePathArray copy];
}

- (NSString *)title
{
    return [self.formatter stringFromDate:self.startTime];
}

- (NSString *)subTitle
{
    return [NSString stringWithFormat:@"point:%d, distance: %.2fm, duration: %.2fs", @(self.locationsArray.count).intValue, [self totalDistance], [self totalDuration]];
}

- (CLLocationDistance)totalDistance
{
    CLLocationDistance distance = 0;
    
    if (self.locationsArray.count > 1)
    {
        CLLocation *currentLocation = [self.locationsArray firstObject];
        for (CLLocation *location in self.locationsArray)
        {
            distance += [location distanceFromLocation:currentLocation];
            currentLocation = location;
        }
    }
    
    return distance;
}

- (NSTimeInterval)totalDuration
{
    return [self.endTime timeIntervalSinceDate:self.startTime];
}

- (NSInteger)numOfLocations;
{
    return self.locationsArray.count;
}

- (NSInteger)numOfAnnotationLocation {

    return self.annotationLocationsArray.count;
}


#pragma mark - NSCoding Protocol

//- (id)initWithCoder:(NSCoder *)aDecoder
//{
//    self = [super init];
//    if (self)
//    {
//        self.startTime = [aDecoder decodeObjectForKey:@"startTime"];
//        self.endTime = [aDecoder decodeObjectForKey:@"endTime"];
//        self.locationsArray = [aDecoder decodeObjectForKey:@"locations"];
//        self.annotationLocationsArray = [aDecoder decodeObjectForKey:@"annotationLocationsArray"];
//        self.filePathArray = [aDecoder decodeObjectForKey:@"filePathArray"];
//      
//    }
//    
//    return self;
//}
//
//- (void)encodeWithCoder:(NSCoder *)aCoder
//{
//    [aCoder encodeObject:self.startTime forKey:@"startTime"];
//    [aCoder encodeObject:self.endTime forKey:@"endTime"];
//    [aCoder encodeObject:self.locationsArray forKey:@"locations"];
//    [aCoder encodeObject:self.annotationLocationsArray forKey:@"annotationLocationsArray"];
//    [aCoder encodeObject:self.filePathArray forKey:@"filePathArray"];
//   
//}

#pragma mark - Life Cycle

- (id)init
{
    self = [super init];
    if (self)
    {
        _startTime = [NSDate date];
        _endTime = _startTime;
        _locationsArray = [[NSMutableArray alloc] init];
        _annotationLocationsArray = [[NSMutableArray alloc] init];
        
    }
    
    return self;
}

- (BOOL)saveRecordWithFileName:(NSString *)fileName {

    NSMutableArray *annotations = [NSMutableArray array];
    for (CLLocation *location in self.annotationLocations) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject: [NSNumber numberWithDouble:location.coordinate.latitude] forKey:@"latitude"];
        [dict setObject: [NSNumber numberWithDouble:location.coordinate.longitude] forKey:@"longitude"];
        [annotations addObject:dict];
    }
    
    NSMutableArray *locations = [NSMutableArray array];
    for (CLLocation *location in self.locationsArray) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject: [NSNumber numberWithDouble:location.coordinate.latitude] forKey:@"latitude"];
        [dict setObject: [NSNumber numberWithDouble:location.coordinate.longitude] forKey:@"longitude"];
        [locations addObject:dict];
    }
    
    // 图片和录音默认存放在以时间命名的目录中
    if (![fileName isEqualToString:  [self.formatter stringFromDate:self.startTime]] ) {
        
        for (NSDictionary *dict in self.filePathArray) {
            
            NSString *imagePath = dict[@"imagePath"];
            NSString *audioPath = dict[@"audioPath"];
            
            if (![imagePath isEqualToString:@"nil"]) {
                NSString *toPath = [FileHelper filePathWithFileName:fileName andFileName:[imagePath lastPathComponent]];
                NSString *atPath = [[FileHelper baseDir] stringByAppendingPathComponent:imagePath];
                BOOL result = [[NSFileManager defaultManager] moveItemAtPath:atPath toPath:toPath error:nil];
                if (result) {
                    [dict setValue:[FileHelper fileNameWithShortPath:toPath] forKey:@"imagePath"];
                }
            }
                if (![audioPath isEqualToString:@"nil"]) {
                    NSString *toPath = [FileHelper filePathWithFileName:fileName andFileName:[audioPath lastPathComponent]];
                    NSString *atPath = [[FileHelper baseDir] stringByAppendingPathComponent:audioPath];
                    BOOL result = [[NSFileManager defaultManager] moveItemAtPath:atPath toPath:toPath error:nil];
                    if (result) {
                        [dict setValue:[FileHelper fileNameWithShortPath:toPath] forKey:@"audioPath"];
                    }
                }
            }
        [[NSFileManager defaultManager] removeItemAtPath:[FileHelper filePathWithPath:[self.formatter stringFromDate:self.startTime]] error:nil];
    }
    
    NSMutableDictionary *fileDict = [NSMutableDictionary dictionary];
    [fileDict setObject:  [self.formatter stringFromDate:self.startTime] forKey:@"startTime"];
    [fileDict setObject: locations forKey:@"locationArray"];
    [fileDict setObject: annotations forKey:@"annotationLocationsArray"];
    [fileDict setObject:  self.filePathArray forKey:@"filePathArray"];
    
    
    NSString *recordPath = [FileHelper filePathWithFileName: fileName andFileName: [fileName stringByAppendingString:@".plist"]];
//    BOOL result = [NSKeyedArchiver archiveRootObject:self toFile:recordPath];

    BOOL result =   [fileDict writeToFile:recordPath atomically:YES];
    return result;
}

@end
